import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Application, Vulnerability } from 'app/model/application.model';
import { Project } from 'app/model/project.model';
import { ApplicationService } from 'app/service/application/application.service';
import { ToastService } from 'app/shared/toast/ToastService';
import { ApplicationsState, ApplicationStateModel } from 'app/store/applications.state';
import { ProjectState } from 'app/store/project.state';
import cloneDeep from 'lodash-es/cloneDeep';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'app-vulnerabilities-list',
    templateUrl: './vulnerabilities.list.html',
    styleUrls: ['./vulnerabilities.list.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class VulnerabilitiesListComponent {

    _filter: string;
    @Input()
    set filter(data: string) {
        this._filter = data;
        this.updateVulns();
    }
    get filter() {
        return this._filter;
    }
    @Input()
    set vulnerabilities(data: Array<Vulnerability>) {
        if (data) {
            this.allVulnerabilities = data;
            this.updateVulns();
        }
    }
    @Input() edit = false;

    application: Application;
    project: Project;
    allVulnerabilities: Array<Vulnerability>;
    filteredVulnerabilities: Array<Vulnerability>;
    showMore: boolean;

    constructor(
        private _applicationService: ApplicationService,
        private _translate: TranslateService,
        private _toast: ToastService,
        private _cd: ChangeDetectorRef,
        private _store: Store
    ) {
        this.project = this._store.selectSnapshot(ProjectState.projectSnapshot);
        this.application = (<ApplicationStateModel>this._store.selectSnapshot(ApplicationsState)).application;
    }

    updateVulns(): void {
        if (this.allVulnerabilities) {
            if (!this.filter) {
                this.filteredVulnerabilities = this.allVulnerabilities;
            } else {
                this.filteredVulnerabilities = this.allVulnerabilities
                    .filter(v => (v.component + ' ' + v.version).indexOf(this.filter) >= 0);
            }
        }
    }

    ignoreVulnerability(index: number): void {
        let v = cloneDeep(this.filteredVulnerabilities[index]);
        v.loading = true;
        v.ignored = !v.ignored;
        this._applicationService.ignoreVulnerability(this.project.key, this.application.name, v)
            .pipe(finalize(() => {
                v.loading = false;
                this._cd.markForCheck();
            }))
            .subscribe(() => this._toast.success('', this._translate.instant('vulnerability_updated')));
    }
}
